<template>
  <xm-container :loading="loading">
    <template v-slot="{ message }">
      <view class="container">
        <view class="scroll-box">
          <view class="title-box">{{ themeName }}</view>
          <view class="bb_box">
            <TnLazyLoad :src="picture" mode="widthFix" class="banner-img" />
            <view class="number_box">
              {{ wordList.length - noListenList.length }}/{{ planPerDayNum }}
            </view>
          </view>

          <view>
            <view class="textBox mt-12">
              <view
                v-for="(item, index) in listenWordList"
                :key="index"
                :id="`scroll${index}`"
              >
                <view class="textLine" :id="`right${index}`">
                  <text
                    :class="currentLine - 1 == index ? 'activeText' : 'text'"
                    >{{ item.content }}</text
                  >
                  <image
                    v-if="currentLine - 1 == index && readstatus == 1"
                    style="
                      width: 40rpx;
                      height: 40rpx;
                      flex-shrink: 0;
                      margin-right: 20rpx;
                    "
                    src="../../static/imgs/play-css-blue.gif"
                    mode=""
                  ></image>
                  <image
                    v-if="currentLine - 1 == index && readstatus == 2"
                    src="../../static/imgs/play_icon.png"
                    style="
                      width: 40rpx;
                      height: 40rpx;
                      flex-shrink: 0;
                      margin-right: 20rpx;
                    "
                    @tap="handleClickAgainPlay(index)"
                  />
                </view>
                <view class="chinese_text" v-if="!listenChinese">
                  {{ item.translate }}
                </view>
                <view
                  class="speakText"
                  v-if="
                    currentLine - 1 == index &&
                    (readstatus == 2 || readstatus == 3)
                  "
                >
                  请跟读...
                </view>

                <!-- <view class="result-wrap" v-if="item.isShowResult"> -->
                <view class="result-wrap">
                  <view
                    class="comment-box"
                    @click="handleClickPlay(item, index, 1)"
                    v-if="item.result && item.result != ''"
                  >
                    <image
                      class="radius-50 pngStyle"
                      :class="item.isPlay ? 'is-translate' : ''"
                      :src="item.isPlay ? playWhiteIconGif : playWhiteIconPng"
                      mode="widthFix"
                    ></image>
                    <view class="result-bar"> {{ item.result.time }}"</view>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>

        <view class="bottom_box">
          <view class="wrap">
            <view class="btn-box" @tap="showWordListPopup">
              <TnIcon name="server" size="30px" color="#BBBBBB" />
              <view
                :class="
                  activeTap == 0 && playing ? 'active-btn-item' : 'btn-item'
                "
                >跟读列表</view
              >
            </view>
            <view class="btn-box">
              <view class="iconBox" v-if="readstatus == 1 || readstatus == 0">
                <image
                  style="width: 60rpx; height: 60rpx; flex-shrink: 0"
                  src="../../static/imgs/mic.png"
                  mode=""
                ></image>
              </view>
              <view class="iconBox" v-if="readstatus == 2">
                <image
                  style="width: 60rpx; height: 60rpx; flex-shrink: 0"
                  src="../../static/imgs/mic_icon.png"
                  mode=""
                ></image>
              </view>
              <view class="iconBox" v-if="readstatus == 3">
                <image
                  style="width: 40rpx; height: 40rpx; flex-shrink: 0"
                  src="../../static/imgs/play-css-blue.gif"
                  mode=""
                ></image>
              </view>

              <view
                :class="
                  activeTap == 1 && readLine !== -1
                    ? 'active-btn-item'
                    : 'btn-item'
                "
                >{{
                  readstatus == 1 || readstatus == 0
                    ? '跟读'
                    : readstatus == 2
                      ? '请跟读'
                      : readstatus == 3
                        ? '跟读中'
                        : ''
                }}</view
              >
            </view>
            <view class="btn-box" @tap="showSetting">
              <TnIcon name="set" size="30px" color="#BBBBBB" />
              <view :class="isAnimation ? 'active-btn-item' : 'btn-item'"
                >学习设置</view
              >
            </view>
          </view>
        </view>
      </view>
      <TnPopup v-model="showSettingPopup" open-direction="bottom">
        <view class="settingBox tn-p-lg">
          <view class="title"> 学习设置 </view>
          <view class="setting_main">
            <view class="setting_line">
              <view class="left_box"> 跟读中文 </view>
              <view class="right_box">
                <TnSwitch
                  v-model="listenChinese"
                  active-color="#5A7BF4"
                  size="sm"
                  @change="changeListenChinese"
                />
              </view>
            </view>
            <view class="setting_line">
              <view class="left_box"> 音频速度 </view>
              <view class="right_box">
                <TnRadioGroup v-model="speed" @change="changeSpeed">
                  <TnRadio :label="1" active-color="#5A7BF4">2.0X</TnRadio>
                  <TnRadio :label="2" active-color="#5A7BF4">1.5X</TnRadio>
                  <TnRadio :label="3" active-color="#5A7BF4">1.0X</TnRadio>
                  <TnRadio :label="4" active-color="#5A7BF4">0.8X</TnRadio>
                </TnRadioGroup>
              </view>
            </view>
            <view class="setting_line">
              <view class="left_box"> 练习顺序 </view>
              <view class="right_box">
                <TnRadioGroup v-model="order" @change="changeOrder">
                  <TnRadio :label="1" active-color="#5A7BF4">顺序</TnRadio>
                  <TnRadio :label="2" active-color="#5A7BF4">随机</TnRadio>
                </TnRadioGroup>
              </view>
            </view>
          </view>
        </view>
      </TnPopup>
      <TnPopup v-model="showListPopup" open-direction="bottom">
        <view class="listen_list_box tn-p-lg">
          <view class="title_line">
            <view class="title"> 今日跟读列表 </view>
            <view class="number_box">
              {{ wordList.length - noListenList.length }}/{{ planPerDayNum }}
            </view>
          </view>
          <view class="word_box">
            <view
              class="word_list"
              v-for="(item, index) in wordList"
              :key="index"
              @tap="toListenWord(index)"
            >
              <view class="word"> {{ item.content }} </view>
              <view class="chinese_word"> {{ item.translate }} </view>
              <view class="play_btn" v-if="listenIndex == index">
                <image
                  src="../../static/images/play-css-blue.gif"
                  mode="widthFix"
                />
              </view>
            </view>
          </view>
        </view>
      </TnPopup>
      <TnPopup
        v-model="showScorpPopup"
        open-direction="center"
        :close-btn="true"
        @close="closeScorpPopup"
      >
        <view class="scorp_box">
          <view class="title"> 专题跟读总结 </view>

          <view class="scorp_Rate">
            <!-- <TnRate
              v-if="showScorpPopup"
              v-model="rateValue"
              :max="3"
              :readonly="true"
              size="80rpx"
              active-color="#FFF700"
              gutter="38rpx"
              :allow-half="false"
            /> -->
            <uv-rate
              :count="3"
              :value="rateValue"
              :readonly="true"
              activeColor="#FFF700"
              gutter="18"
              size="40px"
            />
          </view>

          <view class="scorp_text"
            >{{
              rateValue == 1
                ? 'Needs lmprovement'
                : rateValue == 2
                  ? 'Good'
                  : rateValue == 3
                    ? 'Perfect'
                    : ''
            }}
          </view>
          <view class="detail_box">
            <view class="top_Box">
              <view class="contain_box"> 本节学词 </view>
              <view class="contain_box"> 坚持天数 </view>
              <view class="contain_box"> 累计学词 </view>
            </view>
            <view class="bottom_Box">
              <view class="number_box">
                {{ scropDetail?.todayHadLearnSum }}
              </view>
              <view class="number_box"> {{ scropDetail?.learnDaySum }} </view>
              <view class="number_box"> {{ scropDetail?.hadLearnSum }} </view>
            </view>
          </view>
        </view>
      </TnPopup>
    </template>
  </xm-container>
</template>

<script lang="ts" setup>
import { onMounted, ref, watch, watchEffect } from 'vue'
import { tnNavPage } from '@tuniao/tnui-vue3-uniapp/utils'
import { onLoad, onHide, onUnload } from '@dcloudio/uni-app'
import { xmContainer } from '@/components/xm-container'
import {
  getDailyPlanApi,
  getSceneDetailById,
  readAudioSaveApi,
  readStatusUpdate,
  scoreInfoApi,
  toDown,
  toUp,
  uploadSettingApi,
} from '@/services/api'
import { Base64 } from 'js-base64'
import { useWebsocket, useFormat } from '@/hooks'
import srtParser2 from 'srt-parser-2'
import TnLineProgress from '@tuniao/tnui-vue3-uniapp/components/line-progress/src/line-progress.vue'
import TnIcon from '@tuniao/tnui-vue3-uniapp/components/icon/src/icon.vue'
import type { TnModalInstance } from '@tuniao/tnui-vue3-uniapp/components/modal'
import TnSwitch from '@tuniao/tnui-vue3-uniapp/components/switch/src/switch.vue'
import { useUserStore } from '@/stores'
import TnRate from '@tuniao/tnui-vue3-uniapp/components/rate/src/rate.vue'
const playWhiteIconPng = ref('../../static/imgs/play-white.png')
const playWhiteIconGif = ref('../../static/imgs/play_white.gif')
// var plugin = requirePlugin('WechatSI')
const loading = ref(false)
// let manager = plugin.getRecordRecognitionManager()
const {
  connectWebSocketComment,
  connectWebSocket,
  APPID,
  toBase64,
  handlePlayVideo,
  textTranslate,
  webSocketSendComment,
  webSocketSend,
  webSocketSendOneComment,
  base64toJson,
  handleClickVideo,
  webSocketSendMp3,
  handleCloseVideo,
  splitText,
  closeWebSocket,
  handleDebounce,
  handleGeneratePath,
  handleClearVideo,
} = useWebsocket()
const userStore = useUserStore()
const showSettingPopup = ref(false)
const selectValue1 = ref(true)
const selectValue4 = ref('0')
const selectValue5 = ref('1')
const listenChinese = ref(true)
const repeatTimes = ref(0) //0不循环，-1反复循环
const speakPeople = ref()
const speed = ref()
const order = ref()
const showListPopup = ref(false)
const learnType = ref()
const scenseType = ref()
const planId = ref()
const bookId = ref()
const wordList = ref([] as any)
const listenWordList = ref([] as any)
const listenIndex = ref(0)
const themeName = ref('')
const readstatus = ref(0) //1播放中，2播放结束，3录音中
const currentLine = ref(1)
const noListenList = ref([] as any) //未学习列表
const noListenIndex = ref([] as any) //未学习列表
const scrop = ref(0)
const showScorpPopup = ref(false)
const rateValue = ref(1)
const scropDetail = ref({})
const planPerDayNum = ref()
var nextWordTimeOut = null
const lineArrAll = ref([1, 1, 1, 1, 1, 1, 1, 1, 1, 1])
const repeatReadNum = ref(1)
const showSetting = () => {
  showSettingPopup.value = true
}
const showWordListPopup = () => {
  showListPopup.value = true
}
const toListing = () => {}

onLoad(async (options) => {
  listenChinese.value = userStore.getReadChinese == 1 ? true : false
  speakPeople.value = userStore.getSound_people
  speed.value = userStore.getSound_speed
  order.value = userStore.getSound_order
  learnType.value = Number(options.learnType)
  scenseType.value = options.scenseType
  planId.value = options.planId
  bookId.value = userStore.getBookId
  // if (manager) {
  //   console.log(manager, 'manager关闭录音监听和发送')
  //   // recorderManager.stop()
  //   manager.stop()
  // }
  startWatch()
  await getDailyPlan()
  //获取还没学的列表
  getNoListenList()
  if (noListenList.value.length == 0) {
    await scoreInfo()
    showScorpPopup.value = true
  }
  //随机播放
  if (order.value == 2) {
    setOrderListen()
    console.log('listenIndex.value ', listenIndex.value)
  } else {
    //顺序播放
    setNextListen()
  }
  //获取当前学的单词
  setListenWord()
  startPlaySound()
  console.log('wordList.value', wordList.value)
  console.log('listenWordList.value', listenWordList.value)

  // getNoListenList()
  // setListenWord()
  // console.log(listenWordList.value)
})
watch(
  () => noListenList.value,
  async (newVal, oldVal) => {
    console.log('noListenList.value', oldVal, newVal)
    //第一次读完任务就弹出来
    if (oldVal.length != 0 && newVal.length == 0) {
      console.log('77777777777777777777')
      await scoreInfo()
      showScorpPopup.value = true
    }
  }
)
//设置初始化的顺序播放的单词index
const setNextListen = () => {
  console.log(noListenList.value, 'noListenList.value')
  //随机播放,通过控制listenIndex
  if (noListenList.value.length) {
    //还有未听的优先去遍历未听的列表
    //先获取未听列表的index,然后随机index
    noListenIndex.value = noListenList.value.map((item) => {
      return item.index
    })
    // const index = Math.floor(Math.random() * noListenIndex.value.length)
    listenIndex.value = noListenIndex.value[0]
  } else {
    //没有未听的去遍历总列表
    // const index = Math.floor(Math.random() * wordList.value.length)
    // console.log('index历总列表', wordList.value.length)
    // console.log('index历总列表', index)
    listenIndex.value = 0
  }
}
const scoreInfo = async () => {
  const params = {
    bookId: userStore.getBookId,
    learnType: learnType.value,
    planId: planId.value,
    scenseType: scenseType.value,
    queryTime: new Date().getTime(),
  }
  const data = await scoreInfoApi(params)
  if (data.code === 200) {
    scropDetail.value = data.data
    var leve = 0
    scropDetail.value.leveList.forEach((item) => {
      leve += item.leve
    })
    const scroe = leve / scropDetail.value.leveList.length
    console.log('scroe00000000000000', scroe)
    rateValue.value =
      scroe > 90 && scroe <= 100
        ? 3
        : scroe > 70 && scroe <= 90
          ? 2
          : scroe > 0 && scroe <= 70
            ? 1
            : 0
    console.log('scropDetail.value', scropDetail.value)
  }
}
const toListenWord = (index) => {
  if (promptSound) {
    console.log('播放中停止播放')
    promptSound.stop()
    promptSound = null
  }
  if (readstatus.value == 3) {
    stopSendWebsocket.value = true
    recorderManager.stop()
    // manager.stop()
    // closeWebSocket()
  }
  listenIndex.value = index
  currentLine.value = 1
  setListenWord()
  startPlaySound()
}
var promptSound = null
const startPlaySound = () => {
  readstatus.value = 1
  // listenWordList.value[currentLine.value]
  promptSound = uni.createInnerAudioContext()
  console.log(
    ' listenWordList.value[currentLine.value - 1]',
    listenWordList.value[currentLine.value - 1]
  )
  let src =
    listenWordList.value[currentLine.value - 1].audioList[speakPeople.value - 1]
      .audioUrl
  console.log(src, 'src')
  console.log(currentLine.value, 'currentLine.value')
  promptSound.src = src
  //设置mp3播放速度
  promptSound.playbackRate =
    speed.value == 1
      ? 2.0
      : speed.value == 2
        ? 1.5
        : speed.value == 3
          ? 1.0
          : speed.value == 4
            ? 0.8
            : 1.0

  console.log('开始播放')
  promptSound.play() //执行播放
  promptSound.onEnded(() => {
    promptSound.stop()
    // promptSound.destroy()
    console.log('播放结束')
    readstatus.value = 2
    toSpeaking()
    // if (listenChinese.value) {
    //   //播放翻译的语音
    //   promptSound = uni.createInnerAudioContext()
    //   let src =
    //     listenWordList.value[currentLine.value - 1].translateAudioList[
    //       speakPeople.value - 1
    //     ].audioUrl
    //   promptSound.src = src
    //   //设置mp3播放速度
    //   promptSound.playbackRate =
    //     speed.value == 1
    //       ? 2.0
    //       : speed.value == 2
    //         ? 1.5
    //         : speed.value == 3
    //           ? 1.0
    //           : speed.value == 4
    //             ? 0.8
    //             : 1.0
    //   console.log('开始播放翻译')
    //   console.log(src, 'src')
    //   promptSound.play() //执行播放
    //   promptSound.onEnded(() => {
    //     promptSound.stop()
    //     readstatus.value = 2
    //   })
    //   promptSound.onError((err) => {
    //     uni.showToast({
    //       title: 'mp3播放失败',
    //       icon: 'none',
    //     })
    //   })
    // } else {
    //   readstatus.value = 2
    // }
  })
  promptSound.onError((err) => {
    uni.showToast({
      title: 'mp3播放失败',
      icon: 'none',
    })
  })
}
const handleClickAgainPlay = (index) => {
  readstatus.value = 1
  promptSound = uni.createInnerAudioContext()
  let src =
    listenWordList.value[index].audioList[speakPeople.value - 1].audioUrl
  promptSound.src = src
  //设置mp3播放速度
  promptSound.playbackRate =
    speed.value == 1
      ? 2.0
      : speed.value == 2
        ? 1.5
        : speed.value == 3
          ? 1.0
          : speed.value == 4
            ? 0.8
            : 1.0

  console.log('开始播放')
  promptSound.play() //执行播放
  promptSound.onEnded(() => {
    promptSound.stop()
    // promptSound.destroy()
    console.log('播放结束')
    readstatus.value = 2
  })
  promptSound.onError((err) => {
    uni.showToast({
      title: 'mp3播放失败',
      icon: 'none',
    })
  })
}
// let recorderManagerTimeout = null
// const throttle = () => {
//     if (!timeout) {
//       console.log('2秒')
//       recorderManagerTimeout = setTimeout(() => {
//         console.log('3秒')
//         readstatus.value = 0
//         recorderManager.stop()
//         recorderManagerTimeout = null
//         console.log('2秒没说话停止录音')
//       }, 2000)
//     }
// }
//节流方法
// const throttle = () => {
//   let timeout = null
//   console.log('1秒')
//   return () => {
//     if (!timeout) {
//       console.log('2秒')
//       timeout = setTimeout(() => {
//         console.log('3秒')
//         readstatus.value = 0
//         recorderManager.stop()
//         timeout = null
//         console.log('2秒没说话停止录音')
//       }, 2000)
//     }
//   }
// }
// const throttle = (func, delay) => {
//   let timeout = null

//   return () => {
//     if (!timeout) {
//       timeout = setTimeout(() => {
//         func()
//         timeout = null
//       }, delay)
//     }
//   }
// }
// const debounce = (func, wait) => {
//   console.log('222222')
//   let timeout = null
//   console.log('饭都、timeout', timeout)
//   return () => {
//     clearTimeout(timeout)
//     timeout = setTimeout(() => {
//       console.log('111111')
//       func()
//     }, wait)
//   }
// }
let recorderManagerTimeout = null
// const toStopManger = () => {
//   if (recorderManagerTimeout) {
//     console.log('clearTimeout')
//     clearTimeout(recorderManagerTimeout)
//   }
//   recorderManagerTimeout = setTimeout(() => {
//     console.log('2秒')
//     readstatus.value = 0
//     recorderManager.stop()
//     console.log('2秒没说话停止录音')
//   }, 2000)
// }

const toSpeaking = () => {
  // recorderManager = plugin.getRecordRecognitionManager()
  stopSendWebsocket.value = false
  readstatus.value = 3
  lineArrAll.value = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
  recorderManager.start({
    duration: 120000, // 600000（10 分钟）,默认值 60000（1 分钟）
    numberOfChannels: 1, // 录音通道数，有效值 1/2
    frameSize: 10,
    format: 'pcm', // 音频格式
    sampleRate: 16000, // 采样率
  })
  // clearTimeout(recorderManagerTimeout)
  // recorderManagerTimeout = setTimeout(() => {
  //   console.log('2秒')
  //   readstatus.value = 0
  //   recorderManager.stop()
  //   console.log('2秒没说话停止录音')
  // }, 2000)
  connectWebSocket().then(async (res) => {
    if (res != '') {
      let path = await wavViewPath(frameBufferList.value) //拿到用户的声音
      console.log('拿到用户的声音', path)
      const audioPath = await saveAudio(path)
      console.log('拿到用户的声音audioPath', audioPath)
      listenWordList.value[currentLine.value - 1].result = {
        audio_url: audioPath,
        time: tempFileTime.value,
      }
      if (listenWordList.value[currentLine.value - 1]?.ifTranslate) {
        listenWordList.value[currentLine.value - 2].translateResult = {
          audio_url: audioPath,
          time: tempFileTime.value,
        }
      }
      //朗读句子保存成功，下一句
      repeatReadNum.value = 1
      await readAudioSave(res, audioPath, tempFileTime.value)
      frameBufferList.value = []
    } else {
      repeatReadNum.value += 1
      if (repeatReadNum.value > 2) {
        repeatReadNum.value = 1
        //朗读句子保存成功，下一句
        await readAudioSave(res, '', 0)
        frameBufferList.value = []
      } else {
        uni.showToast({
          title: '未识别到声音，重新跟读',
          icon: 'none',
        })
        readstatus.value = 2
        toSpeaking()
      }
    }
  })
  // initRecord().then(async (res) => {
  //   // isManager = false
  //   if (res.result != '') {
  //     listenWordList.value[currentLine.value - 1].result = {
  //       audio_url: res.tempFilePath,
  //       time: Math.round(res.duration / 1000),
  //     }
  //     if (listenWordList.value[currentLine.value - 1]?.ifTranslate) {
  //       listenWordList.value[currentLine.value - 2].translateResult = {
  //         audio_url: res.tempFilePath,
  //         time: Math.round(res.duration / 1000),
  //       }
  //     }

  //     //朗读句子保存成功，下一句
  //     await readAudioSave(res.result)
  //     frameBufferList.value = []
  //   } else {
  //     uni.showToast({
  //       title: '未识别到声音，重新跟读',
  //       icon: 'none',
  //     })
  //     readstatus.value = 2
  //   }
  // })
  // manager.start({
  //   duration: 10000,
  //   lang: 'zh_CN',
  // })
}
const saveAudio = (filePath: string) => {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: 'https://hr.xming-ai.com/xm/platform/file_upload',
      filePath: filePath,
      name: 'file',
      success: (res) => {
        let data = JSON.parse(res.data)
        if (data.code === 0) {
          resolve(data.data.file_url)
        }
      },
    })
  })
}
const toSend = () => {
  console.log('录音结束345678')
  // isManager = false
  readstatus.value = 0
  recorderManager.stop()
  // manager.stop()
  // manager = null
  // setTimeout(() => {
  //   if (!isManager) {
  //     uni.showToast({
  //       title: '未识别到声音，重新跟读',
  //       icon: 'none',
  //     })
  //     readstatus.value = 2
  //     isManager = false
  //   }
  // }, 1000)
}
// let isManager = false
// const initRecord = () => {
//   return new Promise((resolve, reject) => {
//     console.log('开启录音接受')
//     manager.onStart = function (res: any) {
//       console.log(res + '正在录音')
//       // voiceState.value = "onStart:" + res.msg + "正在录音"
//     }
//     manager.onRecognize = function (res) {
//       console.log('current result', res.result)
//     }
//     manager.onStop = function (res) {
//       isManager = true
//       console.log(res, 'onStop')
//       resolve(res)
//     }
//     manager.onError = (res) => {
//       if (!ifUnload.value) {
//         if (res.retcode == '-30011' || res.retcode == '-30012') {
//           console.log(res)
//           manager.stop()
//           // readstatus.value = 2
//           toSpeaking()
//           reject()
//         } else {
//           console.log(res)
//           resolve({ result: '' })
//         }
//       }
//     }
//   })
// }
onUnload(() => {
  ifUnload.value = true
  console.log('onUnload')
  //关闭录音监听和发送
  stopSendWebsocket.value = true
  if (promptSound) {
    promptSound.stop()
    // manager.onError = null
  }
  if (recorderManager) {
    console.log('关闭录音监听和发送')
    recorderManager.stop()
    // manager.stop()
    // manager.onError = null
  }
  // closeWebSocket()
  currentLine.value = 1
})
import levenShtein from 'js-levenshtein'
const getScorc = (oldText, newText) => {
  let distance = levenShtein(oldText, newText)
  let similarity = 1 - distance / Math.max(oldText.length, newText.length)
  // let totalNum = num + similarity * 50 // 这句话的得分
  let totalNum = 50 + similarity * 50 // 这句话的得分
  return totalNum
}
//朗读声音记录更新
const readAudioSave = async (str, audioPath, userAudioLen) => {
  const params = {
    bookId: userStore.getBookId,
    learnType: learnType.value,
    lessonId: listenWordList.value[currentLine.value - 1].lessonId,
  }
  //有翻译
  if (listenWordList.value[currentLine.value - 1].ifTranslate) {
    params.userTranslateAudioContent = str
    params.userTranslateAudioUrl = audioPath
    params.userTranslateAudioLen = userAudioLen
  } else {
    params.userAudioContent = str
    params.userAudioUrl = audioPath
    params.userAudioLen = userAudioLen
  }
  if (listenWordList.value[currentLine.value - 1].contentId) {
    params.contentId = listenWordList.value[currentLine.value - 1].contentId
  }
  const data = await readAudioSaveApi(params)
  if (data.code === 200) {
    console.log('朗读句子保存成功，下一句')
    //有翻译
    if (!listenWordList.value[currentLine.value - 1].ifTranslate) {
      if (scrop.value == 0) {
        scrop.value = Math.ceil(
          getScorc(listenWordList.value[currentLine.value - 1].content, str)
        )
      } else {
        scrop.value = Math.ceil(
          (scrop.value +
            getScorc(
              listenWordList.value[currentLine.value - 1].content,
              str
            )) /
            2
        )
      }
    }
    console.log(' scrop.value', scrop.value)
    currentLine.value = currentLine.value + 1
    if (currentLine.value <= listenWordList.value.length) {
      // currentLine.value += 1
      startPlaySound()
    } else {
      await setStatus()
      //下一个单词
      // currentLine.value = 1
      // listenIndex.value += 1
      // setListenWord()
      // startPlaySound()
    }
  }
}
// 获取未学习的列表
const getNoListenList = () => {
  noListenList.value = wordList.value.filter((item) => {
    return item.status != 1
  })
  console.log(noListenList.value, 'noListenList.value')
}
//设置随机播放
const setOrderListen = () => {
  console.log(noListenList.value, 'noListenList.value')
  //随机播放,通过控制listenIndex
  if (noListenList.value.length) {
    //还有未听的优先去遍历未听的列表
    //先获取未听列表的index,然后随机index
    noListenIndex.value = noListenList.value.map((item) => {
      return item.index
    })
    const index = Math.floor(Math.random() * noListenIndex.value.length)
    listenIndex.value = noListenIndex.value[index]
  } else {
    //没有未听的去遍历总列表
    const index = Math.floor(Math.random() * wordList.value.length)
    console.log('index历总列表', wordList.value.length)
    console.log('index历总列表', index)
    listenIndex.value = index
  }
}
//学完该单词请求接口更改学习状态
const setStatus = async () => {
  //当前单词听完请求接口保存记录
  const params = {
    bookId: userStore.getBookId,
    learnType: learnType.value,
    lessonId: wordList.value[listenIndex.value].lessonId,
    status: 1,
    leve: scrop.value,
  }
  const data = await readStatusUpdate(params)
  if (data.code === 200) {
    noListenList.value = noListenList.value.filter((item) => {
      return item.lessonId != wordList.value[listenIndex.value].lessonId
    })
    console.log(noListenList.value, 'noListenList.value88888888')
    // setOrderListen()
    if (noListenList.value.length) {
      nextWordTimeOut = setTimeout(() => {
        if (order.value == 2) {
          //随机播放
          setOrderListen()
          currentLine.value = 1
          setListenWord()
          startPlaySound()
        } else {
          if (listenIndex.value + 1 >= wordList.value.length) {
            //顺序播放已听完去全部
            listenIndex.value = 0
            currentLine.value = 1
            setListenWord()
            startPlaySound()
          } else {
            listenIndex.value += 1
            currentLine.value = 1
            setListenWord()
            startPlaySound()
          }
        }
      }, 3000)
    }
  }
}

const startWatch = () => {
  var lastFrame = [] as any
  recorderManager.onStop(function (res) {
    // 监听最后一帧
    // 基础
    if (!stopSendWebsocket.value) {
      webSocketSend(lastFrame, true).then((res) => {
        if (res == 'success') {
        }
      })
      lineArrAll.value = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
      let tempFile = res.tempFilePath //音频文件地址
      tempFilePath.value = tempFile
      tempFileTime.value = Math.round(res.duration / 1000)
      console.log('tempFilePath', tempFilePath)
      console.log('录音时长', res.duration)
      // #ifdef MP-WEIXIN
      const fs = uni.getFileSystemManager()
      // 评分
      fs.readFile({
        //读取文件并转为ArrayBuffer
        filePath: tempFile,
        success(res) {},
      })

      // #endif
    }
  })
  recorderManager.onFrameRecorded(function async(res) {
    // clearTimeout(recorderManagerTimeout)
    // recorderManagerTimeout = setTimeout(() => {
    //   console.log('2秒')
    //   readstatus.value = 0
    //   recorderManager.stop()
    //   console.log('2秒没说话停止录音')
    // }, 2000)
    console.log('收到声音的切片', res)
    const { frameBuffer, isLastFrame } = res
    lastFrame = frameBuffer
    frameBufferList.value.push(frameBuffer)
    // 基础
    // console.log("Hello world")
    webSocketSend(frameBuffer, false).then((res) => {
      if (res == 'success') {
      }
    })
    const intArray = new Int16Array(frameBuffer)
    // 到这一步还能理解，但是 intArray 返回的切片数据太多，才疏学浅没有明白里面具体代表的含义，百度也找了很久没什么资料可以参考，最后找规律发现在每一条的最大值基本代表了现在的振幅，所以直接一步到位取了个最大值，有懂的朋友可以不吝赐教一下
    const amplitude = Math.max(...intArray) // 计算当前帧的振幅
    // 最后将每次的振幅保存下来，进行绘制即可 ， 3276.8 是 根据 采样率及编码码率及你的波形图的最高高度得出的一个合适值， 这个可以随便试一试就出来了

    lineArrAll.value.push(amplitude / 3276.8)
    lineArrAll.value.shift()
    let result = lineArrAll.value.every((item) => {
      return item < 1 // 判断数组的每个元素是否都小于1
    })
    console.log('result', result)
    console.log(lineArrAll.value)
    //跟读结束
    if (result) {
      lineArrAll.value = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
      toSend()
    }

    // closeWebSocket()
  })
  // recorderManager.onDecibelChange(function (res) {
  //   console.log('监听声音分贝变化', res)
  // })
}
const getDailyPlan = async () => {
  const params = {
    // bookId: bookId.value,
    bookId: userStore.getBookId,
    planId: planId.value,
    scenseType: scenseType.value,
    learnType: learnType.value,
  }
  const data = await getDailyPlanApi(params)
  if (data.code == 200) {
    wordList.value = data.data.bookLessonList
    // repeatTimes.value = data.data.repeatTimes
    planPerDayNum.value = data.data.planPerDayNum
    wordList.value.forEach((item, index) => {
      item.index = index
    })
  }
}
//获取当前单词
const setListenWord = () => {
  console.log(learnType.value)
  let wordObjectList = [] //单词列表
  let sentenceList = [] //句子列表
  if (learnType.value == 1 || learnType.value == 3) {
    console.log(listenIndex.value, 'listenIndex.value')
    const object = wordList.value[listenIndex.value]
    console.log(wordList.value, 'wordList.value')
    console.log(object, 'object')
    if (object.userAudioUrl) {
      object.result = {
        audio_url: object.userAudioUrl,
        time: object.userAudioLen,
      }
    }
    //如果听翻译
    if (listenChinese.value) {
      let translateObject = {
        content: object.translate,
        audioList: object.translateAudioList,
        lessonId: object.lessonId,
        ifTranslate: true,
      }
      if (object.userTranslateAudioUrl) {
        translateObject.result = {
          audio_url: object.userTranslateAudioUrl,
          time: object.userTranslateAudioLen,
        }
      }
      if (object.translateResult) {
        console.log('999999999999999999999')
        translateObject.result = {
          audio_url: object.translateResult.audio_url,
          time: object.translateResult.time,
        }
      }
      //翻译的对象
      listenWordList.value = [object, translateObject]
      console.log('listenWordList.value', listenWordList.value)
    } else {
      listenWordList.value = [object]
      console.log('listenWordList.value', listenWordList.value)
    }
    // listenWordList.value.forEach((item, index) => {
    //   if (item.result) {
    //     delete item.result
    //   }
    // })
  }
  // listenWordList.value = [object]
  wordObjectList = listenWordList.value

  if (learnType.value == 2 || learnType.value == 3) {
    const array = wordList.value[listenIndex.value].extendContentList
    array.forEach((item, index) => {
      item.lessonId = wordList.value[listenIndex.value].lessonId

      if (item.userAudioUrl) {
        item.result = {
          audio_url: item.userAudioUrl,
          time: item.userAudioLen,
        }
      }
    })
    array[0].lessonUrl = wordList.value[listenIndex.value].lessonUrl
    array[0].themeName = wordList.value[listenIndex.value].themeName
    console.log(array, 'array')
    //如果听翻译
    if (listenChinese.value) {
      const array2 = []
      array.forEach((item, index) => {
        if (item.translate != '') {
          const translateObject = {
            content: item.translate,
            audioList: item.translateAudioList,
            lessonId: item.lessonId,
            ifTranslate: true,
          } //翻译的对象
          if (item.userTranslateAudioUrl) {
            translateObject.result = {
              audio_url: item.userTranslateAudioUrl,
              time: item.userTranslateAudioLen,
            }
          }
          if (item.translateResult) {
            console.log('888888888888888')
            translateObject.result = {
              audio_url: item.translateResult.audio_url,
              time: item.translateResult.time,
            }
          }
          array2.push(item, translateObject)
        } else {
          array2.push(item)
        }
        console.log(array2, 'array2')
        // array.splice(index + 1, 0, translateObject)
      })
      listenWordList.value = [...array2]
    } else {
      listenWordList.value = [...array]
    }
    // listenWordList.value = [...array]
    sentenceList = listenWordList.value
    sentenceList.forEach((item, index) => {
      if (item.result) {
        delete item.result
      }
    })
  }
  if (learnType.value == 3) {
    listenWordList.value = [...wordObjectList, ...sentenceList]
  }
  themeName.value = listenWordList.value[0].themeName
  picture.value = listenWordList.value[0].lessonUrl
  loading.value = true
}
const ifUnload = ref(false)

const changeListenChinese = async () => {
  if (nextWordTimeOut) {
    clearTimeout(nextWordTimeOut)
  }
  const data = await uploadSettingApi({
    readChineseStatus: listenChinese.value == true ? 1 : 2,
  })
  if (data.code === 200) {
    userStore.setReadChinese(listenChinese.value)
    if (promptSound) {
      console.log('播放中停止播放')
      promptSound.stop()
      promptSound = null
    }
    if (readstatus.value == 3) {
      stopSendWebsocket.value = true
      recorderManager.stop()
      // manager.stop()
      // closeWebSocket()
    }
    listenIndex.value = listenIndex.value
    currentLine.value = 1
    setListenWord()
    startPlaySound()
  } else {
    uni.showToast({
      title: '设置失败',
      icon: 'none',
    })
    listenChinese.value = !listenChinese.value
  }
}
const changeSpeed = async () => {
  const data = await uploadSettingApi({
    playSpeed: speed.value,
  })
  if (data.code === 200) {
    userStore.setSoundSpeed(speed.value)
  } else {
    uni.showToast({
      title: '设置失败',
      icon: 'none',
    })
    speed.value = userStore.getSound_speed
  }
}
const changeOrder = async () => {
  const data = await uploadSettingApi({
    playOrder: order.value,
  })
  if (data.code === 200) {
    userStore.setOrder(order.value)
  } else {
    uni.showToast({
      title: '设置失败',
      icon: 'none',
    })
    order.value = userStore.getSound_order
  }
}
const { encodeWAV, hexToString, buf2hex, wavViewPath } = useFormat()
const innerAudioContext = uni.createInnerAudioContext()
const answer = ref('')
const titleName = ref('')
const currentTime = ref(0)
const picture = ref('')
const asList = ref([] as any)
const audio = ref('')
const playing = ref(false)
let music = uni.createInnerAudioContext()
const overMp3 =
  'http://aia-upload-sz.oss-cn-shenzhen.aliyuncs.com/hr-wechat/mp3/over.mp3'
const niceMp3 =
  'http://aia-upload-sz.oss-cn-shenzhen.aliyuncs.com/hr-wechat/mp3/nice.mp3'
const excellent =
  'http://aia-upload-sz.oss-cn-shenzhen.aliyuncs.com/hr-wechat/mp3/excellent.mp3'
const activeTap = ref(-1) //0为AI朗读，1为智能跟读
const readLine = ref(-1) //当前需要朗读的第几行
const progressPercent = ref(100) //进度条百分比
const readingStatus = ref(0) //0初始值，1朗读中，2评分中
const duration = ref(50000) //当前句子的时长
const currentItem = ref({} as any) //当前朗读的句子
const tempFilePath = ref() //录音文件
const tempFileTime = ref() //录音文件时长
const readList = ref([] as any) //跟读句子列表
const isAnimation = ref(false)
const frameBufferList = ref([])
// 获取录音
const recorderManager = uni.getRecorderManager()
var plugin = requirePlugin('WechatSI')
// let manager = plugin.getRecordRecognitionManager()
let manager = null
const ids = ref([]) //读过的文章id
const styleId = ref('')
const ifZanStatus = ref(0) //0初始值，1赞,2踩
const asDetail = ref({} as any) //文章详情
const stopSendWebsocket = ref(false) //停止发送websocket
var timeout = null as any
const rightIndex = ref(`right${0}`)
const scrollTop = ref(0)
const offsetTop = ref('300')
let scrollPageHeight = 0
let array = [] as AnyObject
let arrayIndex = 0
const currentNum = ref(0)
const asListIndex = ref(-1)
const ossPngList = ref({
  likeOk:
    'http://aia-upload-sz.oss-cn-shenzhen.aliyuncs.com/hr-wechat/static/likeOk.png',
  likeNot:
    'http://aia-upload-sz.oss-cn-shenzhen.aliyuncs.com/hr-wechat/static/likeNot.png',
  stepOk:
    'http://aia-upload-sz.oss-cn-shenzhen.aliyuncs.com/hr-wechat/static/stepOk.png',
  stepNot:
    'http://aia-upload-sz.oss-cn-shenzhen.aliyuncs.com/hr-wechat/static/stepNot.png',
})
const currentStatus = ref('')
// const toListing = () => {
//   //关闭录音监听和发送
//   if (currentStatus.value == 'multiple') {
//     handleClearVideo()
//   }
//   stopSendWebsocket.value = true
//   asListIndex.value = -1
//   refresh()
//   if (activeTap.value !== 0) {
//     initScrollHeight()
//   }
//   activeTap.value = 0
//   console.log('212112')
//   onPlayIconClick()
// }
//换一批
const toChangeNew = () => {
  if (currentStatus.value == 'multiple') {
    handleClearVideo()
  }
  //关闭录音监听和发送
  isAnimation.value = true
  initScrollHeight()
  clearTimeout(timeout)
  playing.value = false
  asListIndex.value = -1
  stopSendWebsocket.value = true
  handleDebounce(() => {
    music.stop()
    refresh()
    getData()
  }, 100)
}
const toReading = () => {
  if (currentStatus.value == 'multiple') {
    handleClearVideo()
  }
  if (readLine.value == -1) {
    clearTimeout(timeout)
    music.stop()
    playing.value = false
    readList.value = JSON.parse(JSON.stringify(asList.value))
    //刷新
    refresh()
    initScrollHeight()
    stopSendWebsocket.value = true
    handleDebounce(() => {
      activeTap.value = 1
      readLine.value = 0
      initScrollHeight()
      readSentence()
    }, 300)
  } else {
    //停止朗读
    handleDebounce(() => {
      refresh()
      closeWebSocket()
      readList.value = JSON.parse(JSON.stringify(asList.value))
      initScrollHeight()
      clearTimeout(timeout)
      //关闭录音监听和发送
      stopSendWebsocket.value = true
      readLine.value = -1
    }, 300)
  }
}
const handleClickPlay = (value: string, index) => {
  if (nextWordTimeOut) {
    clearTimeout(nextWordTimeOut)
  }
  if (![null, undefined, ''].includes(value.result.audio_url)) {
    // readList.value = readList.value.map((item: any, i: any) => {
    //   return {
    //     ...item,
    //     isPlay: i === index,
    //   }
    // })
    listenWordList.value[index].isPlay = true
    handleClickVideo(value.result.audio_url).then(() => {
      listenWordList.value[index].isPlay = false
      if (index == listenWordList.value.length - 1) {
        nextWordTimeOut = setTimeout(() => {
          if (order.value == 2) {
            //随机播放
            setOrderListen()
            currentLine.value = 1
            setListenWord()
            startPlaySound()
          } else {
            if (listenIndex.value + 1 >= wordList.value.length) {
              //顺序播放已听完去全部
              listenIndex.value = 0
              currentLine.value = 1
              setListenWord()
              startPlaySound()
            } else {
              listenIndex.value += 1
              currentLine.value = 1
              setListenWord()
              startPlaySound()
            }
          }
        }, 3000)
      }
    })
    return
  }
}
const closeScorpPopup = () => {
  uni.navigateBack({
    delta: 1,
  })
}
const handleSinglePlay = (item: any, index: number) => {
  if (currentStatus.value == 'multiple') {
    handleClearVideo()
    music.destroy()
    playing.value = true
    asListIndex.value = index
    handlePlayVideo(item.path).then((res) => {
      if (res) {
        playing.value = false
      }
    })
  } else if (currentStatus.value == 'audio') {
    music.stop() // 等待网络的时候音频暂停
    music.src = audio.value //行播放
    music.onPlay(() => {
      playing.value = true
    })
    music.play()
    music.pause()
    music.seek(item.startSeconds)
    music.play()
    music.onTimeUpdate(() => {
      currentTime.value = music.currentTime
      if (music.currentTime >= item.endSeconds) {
        arrayIndex = index
        music.stop()
        playing.value = false
        music = uni.createInnerAudioContext()
        music.src = audio.value
      }
    })
    music.onEnded(() => {
      //播放结束
      music.stop()
      music = uni.createInnerAudioContext()
      music.src = audio.value
      playing.value = false
      asListIndex.value = -1
    })
  }
}
//朗读倒计时
const readSentence = () => {
  stopSendWebsocket.value = false
  rightIndex.value = 'right' + readLine.value
  offsetTop.value = '50%'
  if (readLine.value > readList.value.length - 1 || readLine.value == -1) {
    // 朗读结束刷新
    refresh()
    return
  } else {
    //当前需要朗读的第几行
    currentItem.value = readList.value[readLine.value]
    if (currentStatus.value == 'multiple') {
      duration.value =
        (readList.value[readLine.value].duration || 3) * 1000 + 1500
    } else if (currentStatus.value == 'audio') {
      duration.value =
        (currentItem.value.endSeconds - currentItem.value.startSeconds) * 1000 +
        1500
    }
    startRecord()
  }
}
// 朗读开始录制
// const startRecord = () => {
//   if (!stopSendWebsocket.value) {
//     try {
//       stopSendWebsocket.value = false
//       connectWebSocket().then(async (res) => {
//         let path = await wavViewPath(frameBufferList.value) //拿到用户的声音
//         if (res != '') {
//           readList.value[readLine.value].result = res
//           readList.value[readLine.value].audio_url = path
//           readList.value[readLine.value].isShowResult = true
//         } else {
//           readList.value[readLine.value].isShowResult = true
//           uni.showToast({
//             title: '未识别到文字',
//             icon: 'none',
//           })
//         }
//         frameBufferList.value = []
//       })
//       // 评分
//       connectWebSocketComment(readList.value[readLine.value].text)
//         .then((res) => {
//           if (readLine.value !== -1) {
//           }
//           readList.value[readLine.value].isShowComment = true
//           readList.value[readLine.value].rateValue = Number(res.total_score)
//           if (!readList.value[readLine.value].hasOwnProperty('repeatNum')) {
//             readList.value[readLine.value].repeatNum = 0
//           }
//           //打分成功且分数小于三分且repeatNum = 0则再朗读一遍
//           if (
//             readList.value[readLine.value].rateValue < 3 &&
//             readList.value[readLine.value].repeatNum < 1
//           ) {
//             uni.showToast({
//               title: '不合格再读一遍吧',
//               icon: 'none',
//               duration: 2000,
//             })
//             playSound(readList.value[readLine.value].rateValue).then(() => {
//               let currentIndex = readLine.value
//               readLine.value = -1
//               setTimeout(() => {
//                 readLine.value = currentIndex
//                 readList.value[readLine.value].repeatNum += 1
//                 //关闭websocket
//                 closeWebSocket()
//                 readSentence()
//               }, 300)
//             })
//           } else {
//             //分数大于等于三分或者repeatNum > 0则再继续下一句
//             if (
//               readList.value[readLine.value].repeatNum > 0 &&
//               readList.value[readLine.value].rateValue < 3
//             ) {
//               toScroll(`#scroll${readLine.value}`)
//               readLine.value += 1
//               //关闭websocket
//               closeWebSocket()
//               readSentence()
//             } else {
//               playSound(readList.value[readLine.value].rateValue).then(() => {
//                 toScroll(`#scroll${readLine.value}`)
//                 readLine.value += 1
//                 console.log('99999999999999999999999')
//                 //关闭websocket
//                 closeWebSocket()
//                 readSentence()
//               })
//             }
//           }
//         })
//         .catch((err) => {
//           if (stopSendWebsocket.value) {
//             console.log('手动人为关闭')
//           } else {
//             readList.value[readLine.value].isShowComment = false
//             uni.showToast({
//               title: '评分超时',
//               icon: 'none',
//               duration: 2000,
//             })
//             playSound(readList.value[readLine.value].rateValue).then(() => {
//               let currentIndex = readLine.value
//               readLine.value = -1
//               setTimeout(() => {
//                 readLine.value = currentIndex
//                 //关闭websocket
//                 closeWebSocket()
//                 readSentence()
//               }, 300)
//             })
//           }
//         })
//       readingStatus.value = 1
//       //录音结束倒计时
//       timeout = setTimeout(() => {
//         if (!stopSendWebsocket.value) {
//           endRecord()
//         }
//       }, duration.value)
//       recorderManager.start({
//         duration: 120000, // 600000（10 分钟）,默认值 60000（1 分钟）
//         numberOfChannels: 1, // 录音通道数，有效值 1/2
//         frameSize: 10,
//         format: 'pcm', // 音频格式
//         sampleRate: 16000, // 采样率
//       })
//     } catch (e) {
//       console.log('错误了', e)
//     }
//   } else {
//     console.log('手动关闭结束录制')
//     return
//   }

//   // state.list[currentIndex.value].isShowResult = true
//   // 常规
// }
// 朗读停止
const endRecord = () => {
  recorderManager.stop()
  // manager.stop()
  readingStatus.value = 2
}

//刷新智能跟读
const refresh = () => {
  //关闭录音
  endRecord()
  readLine.value = -1
  readingStatus.value = 0
  duration.value = 0
  currentItem.value = {}
}
const onPlayIconClick = () => {
  if (playing.value) {
    music.pause()
    music.stop()
    currentTime.value = 0
    playing.value = false
  } else {
    if (currentStatus.value == 'multiple') {
      playing.value = true
      const testFun = async function (i: number) {
        asListIndex.value = i
        toScroll(`#right${i}`)
        let num = await handlePath(asList.value[i].path)
        if (i == asList.value.length - 1) {
          playing.value = false
          asListIndex.value = -1
          console.log(currentStatus.value)
          return
        }
        i++
        testFun(i)
      }
      if (asListIndex.value == -1) {
        testFun(0)
      } else {
        testFun(asListIndex.value)
      }
    } else {
      music.play() //执行播放
      music.onPlay(() => {
        playing.value = true
      })
      music.onTimeUpdate(() => {
        currentTime.value = music.currentTime
        //当音频当前播放时间大于字幕每段话开始的时间，就滚动到这段话
        if (music.currentTime > array[arrayIndex]) {
          toScroll(`#right${arrayIndex}`)
          arrayIndex += 1
        }
      })
      music.onEnded(() => {
        //播放结束
        music.stop()
        playing.value = false
        asListIndex.value = -1
      })
    }
  }
}
const handlePath = (str: string) => {
  return new Promise((resolve, reject) => {
    music.stop() // 等待网络的时候音频暂停
    music = uni.createInnerAudioContext()
    music.src = str
    music.play()
    music.onEnded(() => {
      //播放结束
      music.stop()
      music = uni.createInnerAudioContext()
      resolve(true)
    })
  })
}
//初始化页面滚动高度
const initScrollHeight = () => {
  arrayIndex = 0
  scrollPageHeight = 0
  uni.pageScrollTo({
    scrollTop: 0,
    duration: 200,
  })
}

const toScroll = (query: string) => {
  setTimeout(() => {
    uni
      .createSelectorQuery()
      .select(query)
      .boundingClientRect((res) => {
        scrollPageHeight = scrollPageHeight + res?.height
        uni.pageScrollTo({
          // 3. 滚动的距离根据设备的页面高度进行微调（px）
          scrollTop: scrollPageHeight + 13,
          duration: 500,
        })
      })
      .exec()
  }, 50)
}
const str = ref('')
var parser = new srtParser2()

const animation = () => {
  isAnimation.value = false
}
//将'00:01:60,888'格式时间转化为秒
const setTime = (time) => {
  let aTime = time.split(',')[0]
  let sTime = '.' + time.split(',')[1]
  let s = aTime.split(':')[0]
  let f = aTime.split(':')[1]
  let m = aTime.split(':')[2]
  let allTime = Number(s * 3600 + f * 60 + Number(m) + sTime)
  return allTime
}
const getData = () => {
  let params = { ids: ids.value }
  getSceneDetailById(styleId.value, params).then((res) => {
    const { code, data } = res
    if (code === 0) {
      if (data.id !== 0) {
        asDetail.value = data
        str.value = data.subtitles
        let audioMap = []
        if (data.subtitles == '') {
          audioMap = JSON.parse(data.audio_map)
          audioMap.map((item, index) => {
            item.path = item.audio
            item.text = item.content
          })
          asList.value = audioMap
          currentStatus.value = 'multiple'
        } else {
          asList.value = parser.fromSrt(str.value)
          currentStatus.value = 'audio'
          let nstr = ''
          parser.fromSrt(str.value).map((item, index) => {
            // console.log(item.text,"21121")
            nstr += `
							${item.text}`
          })
        }
        ids.value.push(data.id)
        music.src = data.audio
        audio.value = data.audio
        picture.value = data.picture
        ifZanStatus.value = data.like
        readList.value = JSON.parse(JSON.stringify(asList.value))
        currentTime.value = 0
        array = asList.value.map((item, index) => {
          return item.startSeconds
        })

        isAnimation.value = false
        setTimeout(function () {
          loading.value = true
        }, 500)
      } else {
        if (data.total) {
          ids.value = []
          getData()
        } else {
          uni.showToast({
            title: '暂时没有数据!',
            icon: 'none',
            duration: 2000,
          })
        }
      }
    }
  })
}

//点赞
const onZanIconClick = async () => {
  const res = await toUp(asDetail.value.id)
  if (res.code === 0) {
    if (res.status === 1) {
      ifZanStatus.value = 1
      uni.showToast({
        title: '已赞',
        duration: 2000,
      })
    } else if (res.status === 0) {
      ifZanStatus.value = 0
    }
  } else {
    uni.showToast({
      title: res.msg,
      duration: 2000,
    })
  }
}
// 点踩
const onCaiIconClick = async () => {
  const res = await toDown(asDetail.value.id)
  let { code } = res
  if (code === 0) {
    if (res.status === 2) {
      ifZanStatus.value = 2
      uni.showToast({
        title: '已踩',
        duration: 2000,
      })
    } else if (res.status === 0) {
      ifZanStatus.value = 0
    }
  } else {
    uni.showToast({
      title: res.msg,
      duration: 2000,
    })
  }
}

//提示音播放
const playSound = (score) => {
  return new Promise((resolve, reject) => {
    let promptSound = uni.createInnerAudioContext() //提示音
    let sound =
      score < 3
        ? overMp3
        : 3 <= score && score < 4
          ? niceMp3
          : score >= 4
            ? excellent
            : ''
    promptSound.src = sound
    promptSound.play() //执行播放
    promptSound.onPlay(() => {
      console.log('播放中')
    })
    promptSound.onEnded(() => {
      // promptSound.stop()
      promptSound.destroy()
      promptSound.offEnded(() => {
        console.log('取消监听')
      })
      resolve(true)
    })
    promptSound.onError((res) => {
      console.log('播放错误', res.errMsg)
    })
  })
}

//中文翻译成英文
const onTranslate = (answerZh) => {
  plugin.translate({
    lfrom: 'zh_CN',
    lto: 'en_US',
    content: answerZh,
    success: function (res) {
      if (res.retcode == 0) {
        answer.value = res.result
        outputText(answer.value)
      } else {
        console.warn('翻译失败', res)
      }
    },
    fail: function (res) {
      console.log('网络失败', res)
    },
  })
}

//流式输出文字
const outputText = (text) => {
  var index = 0
  const streamOutput = () => {
    if (index < text.length) {
      var currentText = text.substring(0, index + 1)
      answer.value = currentText
      index++
    } else {
      clearInterval(timer)
    }
  }
  let timer = setInterval(streamOutput, 20)
}
</script>

<style lang="scss" scoped>
page {
  max-height: 100vh;
}

.container {
  .settingBox {
    .title {
      width: 100%;
      text-align: center;
    }
    .setting_main {
      margin-top: 20rpx;
      .setting_line {
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: 100rpx;
        .left_box {
          font-size: 28rpx;
          color: #101010;
          font-weight: bold;
        }
        .right_box {
        }
      }
    }
  }
  .listen_list_box {
    .title_line {
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 30rpx;
      .title {
        font-size: 36rpx;
        color: #101010;
        font-weight: bold;
      }
      .number_box {
        font-size: 32rpx;
        color: #6c6c6c;
      }
    }
    .word_box {
      width: 100%;
      height: 500rpx;
      overflow-y: scroll;
      .word_list {
        height: 80rpx;
        display: flex;
        align-items: center;
        border-bottom: 2rpx solid #e0e0e0;
        padding: 0 20rpx;
        .word {
          width: 250rpx;
          font-size: 32rpx;
          color: #333333;
          font-weight: bold;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        }
        .chinese_word {
          width: 250rpx;
          font-size: 28rpx;
          color: #6c6c6c;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
          margin: 0 20rpx;
        }
        .play_btn {
          width: 50rpx;
          height: 50rpx;
          image {
            width: 100%;
            height: 100%;
          }
        }
      }
    }
  }
  .scroll-box {
    width: 100%;
    padding: 48rpx 48rpx 258rpx;

    .title-box {
      background: linear-gradient(90deg, #6b8bfb 0%, #4b49e8 100%);
      //   padding: 24rpx 32rpx;
      width: 100%;
      height: 68rpx;
      line-height: 68rpx;
      text-align: center;
      color: #fff;
      border-radius: 20rpx;
      margin-bottom: 20rpx;
    }
    .bb_box {
      width: 100%;
      position: relative;
      .banner-img {
        width: 100%;
        // height: 384rpx;
        margin-bottom: 24rpx;
      }
      .number_box {
        position: absolute;
        left: 10rpx;
        top: 10rpx;
        color: #fff;
      }
    }

    .textBox {
      width: 100%;
      .textLine {
        width: 100%;
        display: flex;
        align-items: center;
        background-color: #ffffff;
        border-radius: 0 22rpx 22rpx 22rpx;
        margin-bottom: 10rpx;
        .text {
          font-size: 28rpx;
          color: #000000;
          background-color: #ffffff;
          font-weight: bold;
          padding: 20rpx 30rpx;
        }
        .activeText {
          display: block;
          line-height: 64rpx;
          background-color: #fff;
          box-sizing: border-box;
          color: #4b49e8;
          font-size: 40rpx;
          font-weight: bold;
          padding: 20rpx 30rpx;
        }
      }

      .chinese_text {
        padding-left: 20rpx;
      }
      .speakText {
        color: #4b49e8;
        padding-left: 20rpx;
        font-size: 32rpx;
      }
      .result-wrap {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        width: 100%;
        margin-bottom: 24rpx;
        display: grid;

        .comment-box {
          max-width: 500rpx;
          min-height: 88rpx;
          background: #fff;
          display: flex;
          align-items: flex-end;
          padding: 20rpx;
          border-radius: 40rpx;
          background: linear-gradient(90deg, #4b49e8 0%, #6b8bfb 100%);
          font-weight: 400;
          font-size: 28rpx;
          color: #ffffff;
          display: flex;
          align-items: center;
          justify-content: space-between;
          border-radius: 32rpx 0 32rpx 32rpx;
        }

        image {
          width: 48rpx;
          // height: 48rpx;
          border-radius: 50%;
          margin-left: 12rpx;
          margin-right: 60rpx;
        }
      }
    }

    .imgBox {
      display: flex;
      justify-content: flex-end;

      button {
        margin: 0;
        background: none;
        padding: 0;
        margin-right: 16rpx;
      }

      &-icon {
        width: 48rpx;
        height: 48rpx;
      }
    }
  }

  .bottom_box {
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;

    .wrap {
      display: flex;
      justify-content: space-between;
      align-items: flex-end;
      width: 100%;
      padding: 0 30rpx 50rpx;
      height: 258rpx;
      background: #ffffff;

      .btn-box {
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
        width: 200rpx;

        .iconBox {
          width: 88rpx;
          height: 88rpx;
          background: #ffffff;
          box-shadow: 2rpx 0 8rpx 0rpx #bbbbbb;
          border-radius: 50%;
          display: flex;
          justify-content: center;
          align-items: center;
          // box-shadow: inset 0rpx 0rpx 0rpx 0rpx rgba(0, 0, 0, 0.05);
        }

        .active-iconBox {
          background: linear-gradient(90deg, #4b49e8 0%, #6b8bfb 100%);
          box-shadow: 0rpx 8rpx 8rpx 0rpx #f8f8f8;
          border-radius: 50%;
          display: flex;
          justify-content: center;
          width: 120rpx;
          height: 120rpx;
          align-items: center;
          // animation: spin 0.2s 0s 1;
        }

        .refish {
          transition: 1s;
          transform: rotate(360deg);
        }

        .btn-item {
          font-weight: 400;
          font-size: 24rpx;
          color: #666666;
          line-height: 28rpx;
          margin-top: 28rpx;
        }

        .active-btn-item {
          color: #191919;
          font-weight: 400;
          font-size: 24rpx;
          line-height: 28rpx;
          margin-top: 20rpx;
        }
      }
    }
  }
}
.scorp_box {
  width: 670rpx;
  background: linear-gradient(180deg, #abffff 0%, #4362ff 100%);
  padding: 32rpx;
  .title {
    width: 100%;
    text-align: center;
    font-size: 28rpx;
    color: #101010;
    margin-bottom: 70rpx;
    font-weight: bold;
  }
  .scorp_Rate {
    width: 100%;
    display: flex;
    justify-content: center;
    // :deep(.tn-uv-icon__icon:nth-child(2)) {
    //   margin-bottom: 50rpx;
    // }
    :deep(.uv-rate__content__item:nth-child(2)) {
      bottom: 32rpx;
    }
  }
  .scorp_text {
    width: 100%;
    text-align: center;
    font-size: 56rpx;
    color: #ffffff;
    margin-bottom: 50rpx;
    font-weight: bold;
  }
  .detail_box {
    width: 100%;
    .top_Box {
      width: 100%;
      height: 130rpx;
      display: flex;
      justify-content: space-between;
      background: #f0f1f5;
      border-radius: 30rpx 30rpx 0 0;
      .contain_box {
        height: 130rpx;
        width: 33.3%;
        line-height: 130rpx;
        text-align: center;
        font-size: 32rpx;
        color: #4f4f4f;
        font-weight: bold;
      }
    }
    .bottom_Box {
      width: 100%;
      height: 160rpx;
      display: flex;
      justify-content: space-between;
      background: #ffffff;
      border-radius: 0 0 30rpx 30rpx;

      .number_box {
        height: 160rpx;
        width: 33.3%;
        line-height: 160rpx;
        text-align: center;
        font-size: 56rpx;
        color: #000000;
        font-weight: bold;
      }
    }
  }
}

:deep(.tn-modal) {
  border-radius: 48rpx !important;
  background: linear-gradient(164deg, #dee2ff 2%, #ffffff 100%);
  width: 556rpx !important;
  height: 344rpx !important;
}

:deep(.tn-modal__title) {
  font-size: 32rpx !important;
  color: #000000;
  font-weight: 600 !important;
  padding-top: 48rpx !important;
}

:deep(.tn-modal__content--text) {
  font-size: 24rpx;
  color: #666666;
}

:deep(.tn-modal__operation) {
  border-top: none !important;
  justify-content: center;
  margin-top: 48rpx !important;
}

:deep(.tn-modal__operation-btn) {
  width: 460rpx !important;
  height: 80rpx !important;
  background: linear-gradient(90deg, #4b49e8 0%, #6b8bfb 100%);
  border-radius: 40rpx;
  flex-grow: initial !important;
  font-size: 32rpx !important;
  color: #ffffff !important;
  line-height: 80rpx;
}

:deep(.tn-modal__content) {
  padding-top: 32rpx !important;
}

@keyframes spin {
  0% {
    scale: 0.9;
  }

  25% {
    scale: 1;
  }

  50% {
    scale: 1.1;
  }

  75% {
    scale: 1;
  }

  100% {
    scale: 0.9;
  }
}

/*点赞图标放大动画开始*/
@keyframes myfirst {
  0% {
    scale: 0.9;
    transform: rotate(10deg);
  }

  100% {
    scale: 1;
    transform: rotate(0deg);
  }
}

.animation {
  animation: myfirst 0.5s;
}
:deep(.tn-lazy-load__image) {
  border-radius: 16rpx !important;
}
</style>
